package cn.jbolt.ai.resource.function.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.resource.function.enums.SyncStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jbolt.ai.resource.function.dao.AiFunctionParamMapper;
import cn.jbolt.ai.resource.function.service.AiFunctionParamService;
import cn.jbolt.ai.resource.function.entity.AiFunctionParam;
import cn.jbolt.ai.resource.function.service.AiFunctionResourceService;
import cn.jbolt.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AiFunctionParamServiceImpl extends ServiceImpl<AiFunctionParamMapper, AiFunctionParam> implements AiFunctionParamService {

    @Autowired
    private AiFunctionResourceService functionResourceService;


    @Override
    public Result getParamById(Long id) {
        AiFunctionParam param = this.getById(id);
        if (param != null) {
            return Result.success(param);
        } else {
            return Result.error("AI函数参数不存在");
        }
    }

    @Override
    public Result getList(String keywords, Long functionId) {
        QueryWrapper<AiFunctionParam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ai_function_id", functionId);
        if (StrUtil.isNotBlank(keywords)) {
            queryWrapper.and(wrapper -> wrapper.like("param_name", keywords)
                    .or().like("brief_info", keywords).or().like("type", keywords).
                    or().like("default_value", keywords));
        }
        queryWrapper.orderByAsc("sort_rank");
        return Result.success(this.list(queryWrapper));
    }

    @Override
    @Transactional
    public Result add(AiFunctionParam param) {

        Result checkResult = functionResourceService.checkFunctionStatus(param.getAiFunctionId());
        if (checkResult.isError()) {
            return checkResult;
        }
        //处理参数的排序
        param.setSortRank(getMaxSortRank(param.getAiFunctionId()) + 1);
        boolean save = this.save(param);
        if (save) {
            return functionResourceService.updateFunctionParamCount(param.getAiFunctionId(), 1);

        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 查询最后一个参数的序号
     *
     * @param aiFunctionId
     * @return
     */
    private Integer getMaxSortRank(Long aiFunctionId) {
        AiFunctionParam param = this.getOne(new QueryWrapper<AiFunctionParam>().
                eq("ai_function_id", aiFunctionId).orderByDesc("sort_rank").last("limit 1"));
        return param == null ? 0 : param.getSortRank();
    }

    @Override
    public Result update(AiFunctionParam param) {
        Result checkResult = functionResourceService.checkFunctionStatus(param.getAiFunctionId());
        if (checkResult.isError()) {
            return checkResult;
        }
        boolean updated = updateById(param);
        if (updated) {
            return Result.success();
        } else {
            return Result.error("更新失败");
        }
    }

    @Override
    @Transactional
    public Result del(Long id) {
        AiFunctionParam param = this.getById(id);
        if (param != null) {
            Result checkResult = functionResourceService.checkFunctionStatus(param.getAiFunctionId());
            if (checkResult.isError()) {
                return checkResult;
            }
            if (removeById(id)) {
                return functionResourceService.updateFunctionParamCount(param.getAiFunctionId(), -1);

            } else {
                return Result.error("删除失败");
            }
        } else {
            return Result.error("AI函数参数不存在");
        }
    }

    @Override
    public Result toggleEnable(Long id) {
        AiFunctionParam param = this.getById(id);
        if (param == null) {
            return Result.error("AI函数参数不存在");
        }
        Result checkResult = functionResourceService.checkFunctionStatus(param.getAiFunctionId());
        if (checkResult.isError()) {
            return checkResult;
        }
        Boolean enable = !param.getRequired();
        boolean update = this.update(new UpdateWrapper<AiFunctionParam>().eq("id", id).set("is_required", enable));
        if (update) {
            return Result.success(update);
        } else {
            return Result.error("修改失败");
        }
    }


    @Override
    @Transactional
    public void syncNativeFunctionParams(Long functionResourceId, List<AiFunctionParam> params, SyncStrategy strategy) {
        // 获取数据库中的参数
        List<AiFunctionParam> dbParams = this.list(new QueryWrapper<AiFunctionParam>().
                eq("ai_function_id", functionResourceId));

        switch (strategy) {
            case FULL:
                // 删除所有旧参数
                if (!dbParams.isEmpty()) {
                    this.remove(new QueryWrapper<AiFunctionParam>().
                            eq("ai_function_id", functionResourceId));
                }
                // 保存所有新参数
                if (!params.isEmpty()) {
                    this.saveBatch(params);
                }
                break;

            case INCREMENT:
                // 删除不存在于本地的参数
                if (!dbParams.isEmpty()) {
                    Set<String> localParamNames = params.stream()
                            .map(AiFunctionParam::getParamName)
                            .collect(Collectors.toSet());

                    List<AiFunctionParam> paramsToDelete = dbParams.stream()
                            .filter(dbParam -> !localParamNames.contains(dbParam.getParamName()))
                            .collect(Collectors.toList());

                    if (!paramsToDelete.isEmpty()) {
                        this.removeByIds(paramsToDelete.stream()
                                .map(AiFunctionParam::getId)
                                .collect(Collectors.toList()));
                    }
                }

                // 更新已存在参数的sortRank并添加新参数
                Map<String, AiFunctionParam> dbParamMap = dbParams.stream()
                        .collect(Collectors.toMap(AiFunctionParam::getParamName, param -> param));

                List<AiFunctionParam> paramsToAdd = new ArrayList<>();
                List<AiFunctionParam> paramsToUpdate = new ArrayList<>();

                for (AiFunctionParam param : params) {
                    AiFunctionParam existingParam = dbParamMap.get(param.getParamName());
                    if (existingParam != null) {
                        // 更新已存在参数的sortRank
                        existingParam.setSortRank(param.getSortRank());
                        existingParam.setType(param.getType());
                        paramsToUpdate.add(existingParam);
                    } else {
                        // 添加新参数
                        paramsToAdd.add(param);
                    }
                }

                // 批量更新和添加
                if (!paramsToUpdate.isEmpty()) {
                    this.updateBatchById(paramsToUpdate);
                }
                if (!paramsToAdd.isEmpty()) {
                    this.saveBatch(paramsToAdd);
                }
                break;
        }

    }

    public List<AiFunctionParam> getParamListByFunctionId(Long functionId) {
        return this.list(new QueryWrapper<AiFunctionParam>().eq("ai_function_id", functionId));
    }

    @Override
    public List<AiFunctionParam> getParamListByFunctionId(List<String> functionIdList) {
        return this.list(new QueryWrapper<AiFunctionParam>().in("ai_function_id", functionIdList));
    }
}
